using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;

namespace Code5Systems.FormMaster
{

	public partial class FormMasterFiles : DotNetNuke.Entities.Modules.PortalModuleBase
	{
		
#region  Web Form Designer Generated Code
		
		
		//This call is required by the Web Form Designer.
		[System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent()
		{
			
		}
		
		protected System.Web.UI.WebControls.LinkButton cmdClear;
		protected System.Web.UI.WebControls.LinkButton cmdSearch;
		protected System.Web.UI.WebControls.TextBox txtFileName;
		protected System.Web.UI.WebControls.DataGrid dgFiles;
		protected System.Web.UI.WebControls.Label lblDeleteMsg;
		
		//NOTE: The following placeholder declaration is required by the Web Form Designer.
		//Do not delete or move it.
		private System.Object designerPlaceholderDeclaration;
		
		private void Page_Init(System.Object sender, System.EventArgs e)
		{
			//CODEGEN: This method call is required by the Web Form Designer
			//Do not modify it using the code editor.
			InitializeComponent();
		}
		
#endregion
		
		
#region Private Members
		
		
		private DotNetNuke.Entities.Modules.PortalModuleBase _loaderCtl;
		private string strSortField = "OrigFileName";
		private string strSortDir = " Asc";
		private string strFindBy = "";
		private Code5Systems.FormMaster.Business.FormFileDataController objFormFileCtl;
		private string strOperationSuccess;
		
#endregion
		
		
#region Event Handlers

		protected void Page_Load(System.Object sender, System.EventArgs e)
		{
			try
			{
				this.LoaderCtl = (PortalModuleBase) this.Parent.Parent;
				
				Localization.LocalizeDataGrid(ref dgFiles, LocalResourceFile);
				
				this.lblDeleteMsg.Text = Localization.GetString("NoDeleteMsg", this.LocalResourceFile);
				
				//Check if the user has Sorted the DataGrid
				if (!(ViewState["SortField"] == null))
				{
					strSortField = System.Convert.ToString(ViewState["SortField"]);
				}
				
				//And in what Sort Order
				if (!(ViewState["SortDirection"] == null))
				{
					strSortDir = System.Convert.ToString(ViewState["SortDirection"]);
				}
				
				//Check if the user has Searched
				if (!(ViewState["FindBy"] == null))
				{
					strFindBy = System.Convert.ToString(ViewState["FindBy"]);
				}
				
				strOperationSuccess = Localization.GetString("OperationSuccess", this.LocalResourceFile);
				
				objFormFileCtl = new Code5Systems.FormMaster.Business.FormFileDataController();
				
				if (!Page.IsPostBack)
				{
					BindGrid();
				}
				
				if ((!Request.UserAgent.Contains("MSIE")) || Request.Browser.Platform.Contains("Mac"))
				{
					if (DotNetNuke.Framework.AJAX.IsInstalled())
					{
						Utility.DisableAjax(this);
					}
				}
				
			}
			catch (Exception exc)
			{
				Exceptions.ProcessModuleLoadException(LoaderCtl, exc);
			}
		}

		protected void dgFiles_ItemCommand(System.Object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			string strCommandName = default(string);
			
			try
			{
				strCommandName = ((LinkButton) e.CommandSource).CommandName;
				
				switch (strCommandName)
				{
					
				case "Delete":
					Label oLabel = (Label) (e.Item.FindControl("lblFileDataId"));
					
					if (oLabel != null)
					{
						objFormFileCtl.DeleteFile(int.Parse(oLabel.Text));
					}
					
					BindGrid();
					break;
					
			}
			
		}
		catch (IOException ioexc)
		{
			DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, ioexc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
		}
		catch (SqlException dbexc)
		{
			DotNetNuke.UI.Skins.Skin.AddModuleMessage(this, dbexc.Message, DotNetNuke.UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError);
		}
		catch (Exception exc)
		{
			Exceptions.ProcessModuleLoadException(this, exc);
		}
		
	}

		protected void dgFiles_PageIndexChanged(System.Object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			dgFiles.CurrentPageIndex = e.NewPageIndex;
			BindGrid();
		}
	
		//Set up the order by Save to ViewState and bind the DataGrid
		protected void dgFiles_SortCommand(System.Object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
		{
			if (strSortField == e.SortExpression)
			{
				if (strSortDir == " Asc")
				{
					strSortDir = " Desc";
				}
				else if (strSortDir == " Desc")
				{
					strSortDir = " Asc";
				}
			}
			else
			{
				strSortDir = " Asc";
			}
		
			strSortField = e.SortExpression;
		
			ViewState.Add("SortField", strSortField);
			ViewState.Add("SortDirection", strSortDir);
		
			BindGrid();
		}
	
		//Add the Delete Onclick Event Message
		//Check if the File is related to a Form Data Record, if so hide the Delete button
		protected void dgFiles_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			Label oLabel = default(Label);
		
			oLabel = (Label) (e.Item.FindControl("lblFormDataId"));
			if (oLabel != null)
			{
				LinkButton cmdDelete = default(LinkButton);
				cmdDelete = (LinkButton) (e.Item.Cells[4].Controls[0]);
			
				if ((oLabel.Text == "0") || (oLabel.Text == string.Empty))
				{
					cmdDelete.CausesValidation = false;
					cmdDelete.Attributes.Add("onclick", "javascript:return confirm(\'" + Localization.GetString("DeleteDataMessage", LocalResourceFile) + "\');");
				}
				else
				{
					cmdDelete.Visible = false;
				}
			}

			oLabel = (Label)(e.Item.FindControl("lblDownloadLink"));
			if (oLabel != null)
			{
				var dataItem = e.Item.DataItem as DataRowView;
				oLabel.Text = GetDownloadLink(int.Parse(dataItem.Row[0].ToString()), dataItem.Row[8].ToString());
			}
		}
	
		//Set up the search query and bind the DataGrid
		protected void cmdSearch_Click(System.Object sender, System.EventArgs e)
		{
		
			strFindBy = "";
		
			if (this.txtFileName.Text != string.Empty)
			{
				strFindBy = "OrigFileName Like \'%" + this.txtFileName.Text + "%\' ";
			}
		
			ViewState.Add("FindBy", strFindBy);
		
			BindGrid();
		}
	
		//Clear the search query and bind the DataGrid
		protected void cmdClear_Click(System.Object sender, System.EventArgs e)
		{
			strFindBy = "";
			this.txtFileName.Text = "";
			ViewState.Remove("FindBy");
			BindGrid();
		}
	
#endregion
	
	
#region Data Bind Methods
	
	private void BindGrid()
	{
		
		DataTable dt = objFormFileCtl.GetFilesByModuleID(ModuleId);
		
		DataView oDataView = dt.DefaultView;
		
		oDataView.RowFilter = strFindBy;
		
		oDataView.Sort = strSortField + strSortDir;
		
		this.dgFiles.DataSource = oDataView;
		
		try
		{
			this.dgFiles.DataBind();
		}
		catch (Exception e)
		{
			if (e.Message.IndexOf("Invalid CurrentPageIndex") > -1)
			{
				if (dgFiles.CurrentPageIndex > 0)
				{
					dgFiles.CurrentPageIndex = 0;
					this.dgFiles.DataBind();
				}
			}
			else
			{
				throw (e);
			}
		}
		
	}
	
	public string GetDownloadLink(int fileDataId, string origFileName)
	{
		string strLink = default(string);
		strLink = "<a href=\"" + this.ControlPath + "Render.aspx";
		strLink += "?FileDataId=" + fileDataId.ToString() + "\">" + origFileName + "</a>";
		
		return strLink;
	}
#endregion
	
	
#region Public Properties
	public PortalModuleBase LoaderCtl
	{
		get
		{
			if (_loaderCtl == null)
			{
				_loaderCtl = this;
			}
			
			return _loaderCtl;
		}
		set
		{
			_loaderCtl = value;
		}
	}
#endregion
}

}


